/**
 * Created by sxx on 2017/5/3.
 */
import "./index.less";
import "../../../unit/common/js/bootstrap_js/bootstrap-datetimepicker.js";
import "../../../unit/common/js/bootstrap_js/bootstrap-datetimepicker.zh-CN.js";

import bidListTpl from "./apply_list.handlebars";
import paginationTpl from "./paging.handlebars";

let token = sessionStorage.getItem('token');
let reseIndex = sessionStorage.getItem('reseIndex');
let orgId = sessionStorage.getItem('orgId');
if (orgId == null || orgId =='') {
    location.href = HOST_FRT+'/logins/login.html';
}

var ApplyList = {
    pageNo: 1,
    pageSize: 20,
    maxPage: 1,
    isFirstPage: false,
    isLastPage: false,
    total: 0,
    data:{},
    init: function() {
        this.getData()
            .then(this.renderList)
            .then(this.renderPagination)
            .then(this.bindEvent);
    },
    getData: function() {
        let self = ApplyList;
        return new Promise((resolve, reject) => {
            let data = {};
            let header = {
                    'access_token': token,
                    'login_type': 'ums',
                    'pageNo':self.pageNo,
                    'pageSize':self.pageSize
                };
            if(self.data.splrNam!='' && self.data.splrNam!=null){
                data.splrFullName = self.data.splrNam;
            }
            $.ajax({
                url: HOST_ADDR + '/cpmp/splrWdot/getSplrWdotList',
                type: 'post',
                dataType: 'json',
                headers: header,
                data:JSON.stringify(data),
                contentType: "application/json",
                success: function(resp) {
                    if (resp.success) {
                        console.log(resp);
                        resolve(resp);
                    } else {
                        alert(resp.msgInf);
                    }
                },
                error: function(err) {
                    console.log(err);
                }
            });
        });
    },
    // 渲染列表

    renderList: function(resp) {
        let self = ApplyList;
        var approveSts = {
            "02":"通过",
            "03":"不通过"
        };
        if(resp.data==''||resp.data==null){
            self.total = 0;
            self.isFirstPage = self.pageNo === 1;
            self.maxPage = 1;
            self.isLastPage = true;
        }else{
            self.total = resp.data.count;
            self.isFirstPage = self.pageNo === 1;
            self.maxPage = Math.ceil(self.total / self.pageSize);
            console.log(resp.data);
            $.each(resp.data.list,function(index,item){
                item.aplyCtt = item.aplyCtt ? item.aplyCtt : '';
                item.wdotDeptAdtFmt = approveSts[item.wdotDeptAdtSts] ? approveSts[item.wdotDeptAdtSts]+": "+(item.wdotDeptAdtMsg==null ? '': item.wdotDeptAdtMsg) : '';
                item.wdotMngAdtFmt = approveSts[item.wdotSplrMngAdtSts] ? approveSts[item.wdotSplrMngAdtSts]+": "+(item.wdotSplrMngAdtMsg==null ? '': item.wdotSplrMngAdtMsg) : '';
                item.reActiveCtt = item.reActiveCtt ? item.reActiveCtt : '';
                item.reActiveDeptAdtFmt = approveSts[item.reActDeptAdtSts] ? approveSts[item.reActDeptAdtSts] +": "+(item.reActiveDeptAdtMsg==null ? '': item.reActiveDeptAdtMsg) : '';
                item.reActiveMngAdtFmt = approveSts[item.reActSplrMngAdtSts] ? approveSts[item.reActSplrMngAdtSts] +": "+(item.reActiveSplrMngAdtMsg==null ? '': item.reActiveSplrMngAdtMsg) : '';

                item.approveAvailabel1 = (item.wdotDeptAdtSts=='02' && item.wdotSplrMngAdtSts!='02' && item.wdotSplrMngAdtSts!='03');    // 申请淘汰审批审批   02 成功，  03 失败
                item.approveAvailabel2 = (item.reActDeptAdtSts=='02' && item.reActSplrMngAdtSts!='02' && item.reActSplrMngAdtSts!='03' && item.reActAplyId!=null);   // 重新启用审批       02 成功，  03 失败
            });
            // 处理数据end
            if (self.pageNo * self.pageSize >= self.total) {
                self.isLastPage = true;
            } else {
                self.isLastPage = false;
            }
            var resultHtml = bidListTpl({ applyList: resp.data.list });
        }
        $('.J_apply-list').html(resultHtml);
    },

    // 渲染分页
    renderPagination: function() {
        let self = ApplyList;
        let pageList = [];
        for (let i = 0; i < self.maxPage; i++) {
            pageList.push({ idx: i + 1 });
        }
        let paginationHtml = paginationTpl({
            begin: (self.pageNo - 1) * self.pageSize + 1,
            end: self.isLastPage ? self.total : self.pageNo * self.pageSize,
            total: self.total,
            isLastPage: self.isLastPage,
            isFirstPage: self.isFirstPage,
            pageList: pageList

        });
        $('.J_pagination').html(paginationHtml);
        $('.page-item').each((index, item) => {
            if ($(item).data('index') === self.pageNo) {
                $(item).addClass('active');
            }
            var basepage = self.pageNo;
            if(basepage<=5){
                basepage = 5;
            }
            if((-5 <= (parseInt($(item).data('index'))-basepage)) && ((parseInt($(item).data('index'))-basepage)<=5)){
                $(item).removeClass('hidden');
                $(item).find("span").removeClass("hidden");
            }else{
                $(item).addClass('hidden');
                $(item).find("span").addClass("hidden");
            }
        });
    },

    // 绑定事件
    bindEvent: function() {
        let self = ApplyList;
        $('.J_prev').unbind().click(function() {
            if (self.pageNo > 1) {
                self.pageNo = self.pageNo - 1;
                self.getData()
                    .then(self.renderList)
                    .then(self.renderPagination)
                    .then(self.bindEvent);
            }
        });
        $('.J_next').unbind().click(function() {
            console.log('J_next');
            if (self.pageNo < self.maxPage) {
                console.log('aaa');
                self.pageNo = self.pageNo + 1;
                self.getData()
                    .then(self.renderList)
                    .then(self.renderPagination)
                    .then(self.bindEvent);
            }
        });
        $('.page-item').off().on('click', function() {
            let $item = $(this);
            console.log('aaaa');
            if (!$item.hasClass('active')) {
                self.pageNo = $item.data('index');
                self.getData()
                    .then(self.renderList)
                    .then(self.renderPagination)
                    .then(self.bindEvent);
            }
        });

        // 点击淘汰按钮时传参数
        $(".btnSub").unbind().click(function(){
            var aplyId = $(this).parent().parent().attr("aplyId");
            var reActAplyId = $(this).parent().parent().attr("reActAplyId");
            var splrName = $(this).parent().parent().attr("splrNam");
            var action = $(this).attr("action");
            var titleName = '请输入审批意见：   '+(action=='wdot' ? '淘汰':'启用')+'[['+splrName+']]';
            $("#myModalLabel").html(titleName);
            $("#myModalLabel").attr("aplyId",aplyId);
            $("#myModalLabel").attr("reActAplyId",reActAplyId);
            $("#myModalLabel").attr("action",action);
        });

        var flg = true;
        // 审批
        $(".endReason").unbind().click(function(){
            if(!flg){
                setTimeout(function(){flg=true;},3000);
                return false;
            }else{
                flg = false;
            }
            var aplyId = $("#myModalLabel").attr("aplyId");
            var reActAplyId = $("#myModalLabel").attr("reActAplyId");
            var action = $("#myModalLabel").attr("action");
            var adtSts = $(this).attr("appval");   //   02 通过    03 不通过
            var adtMsg = $(".endInfo").val();
            var data={
                "adtMsg":adtMsg,
                "adtSts":adtSts
            };
            var url='';
            if(action=='wdot'){
                url = HOST_ADDR + '/cpmp/splrWdot/splrMngAdt';
                data.aplyId = aplyId;
            }else{
                url = HOST_ADDR + '/cpmp/splrReAct/splrMngAdt';
                data.aplyId = reActAplyId;
            }
            $.ajax({
                url: url,
                type: 'post',
                dataType: 'json',
                headers: {
                    'access_token': token,
                    'login_type': 'ums'
                },
                data:JSON.stringify(data),
                contentType: "application/json",
                success: function(resp) {
                    if (resp.success) {
                        console.log(resp);
                        alert("审批成功");
                        flg = true;
                        var html=adtSts==('02'? "通过" : "不通过")+": "+(adtMsg==null ? '' : adtMsg);
                        if(action=='wdot'){
                            $("tr.odd[aplyId="+aplyId+"]").find(".operation1").html(html);
                        }else{
                            $("tr.odd[reActAplyId="+reActAplyId+"]").find(".operation2").html(html);
                        }
                    } else {
                        alert(resp.msgInf);
                    }
                    $("#myModal").modal('hide');
                },
                error: function(err) {
                    console.log(err);
                }
            });
        });

        // 搜索
        $('.searchSplr').unbind().click(function(){
            var searNam = jQuery('.searNam').val();
            self.pageNo = 1;
            self.data = {};
            if (searNam != '' && searNam != null) {
                self.data.splrNam = searNam;
            }
            console.log(self.data);
            self.getData()
                .then(self.renderList)
                .then(self.renderPagination)
                .then(self.bindEvent);
        });
    },
};

App.init();
ApplyList.init();

